package com.ld.admin.tag.plugin;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.servlet.jsp.JspTagException;
import javax.servlet.jsp.JspWriter;
import javax.servlet.jsp.tagext.TagSupport;

import com.ld.shieldsb.common.core.collections.ListUtils;
import com.ld.shieldsb.common.core.util.StringUtils;

import lombok.Data;
import lombok.EqualsAndHashCode;

/**
 * 
 * 上传附件标签
 * 
 * @ClassName ImagesUploadPluginTag
 * @author <a href="mailto:550827627@qq.com" target="_blank">刘金浩</a>
 * @date 2019年7月18日 上午11:38:42
 *
 */
@Data
@EqualsAndHashCode(callSuper = true)
public class AffixUploadPluginTag extends TagSupport {

    private String fileId;
    private String fileName;
    private String filePath;
    private String fileIdValue;
    private String fileNameValue;
    private String shieldSettings;
    private boolean multi = false;
    private String buttonText = "上传附件";
    private String filePathValue;
    private boolean required = false;
    private boolean show = false;
    private String uploadMethod = "remote"; // 上传方式remote local

    private String dataHandlerImpl = ""; // excel 本地上传后数据处理实现类
    /**
     * @Fields serialVersionUID :
     */
    private static final long serialVersionUID = 1L;

    public int doStartTag() throws JspTagException {
        return EVAL_PAGE;
    }

    public int doEndTag() throws JspTagException {
        JspWriter out = null;
        try {
            out = this.pageContext.getOut();
            out.print(end().toString());
        } catch (IOException e) {
            e.printStackTrace();
        }
        return EVAL_PAGE;
    }

    public StringBuffer end() {
        StringBuffer sb = new StringBuffer();
        sb.append("<!-- fileName存放文件编号 -->\r\n");
        sb.append("<input class=\"fileId " + (required ? "" : "ignore") + "\" name=\"" + fileId + "\" type=\"hidden\" value=\""
                + fileIdValue + "\"/>");
        sb.append("<!-- fileName存放文件名称 -->\r\n");
        sb.append("<input class=\"fileName " + (required ? "" : "ignore") + "\" name=\"" + fileName + "\" type=\"hidden\" value=\""
                + fileNameValue + "\"/>");
        sb.append("<!-- filePath存放文件路径 -->\r\n");
        sb.append("<input class=\"filePath " + (required ? "" : "ignore") + "\"  name=\"" + filePath + "\" type=\"hidden\" value=\""
                + filePathValue + "\"/>");
        setDataHandlerImpl(sb);
        sb.append("<!-- ignore忽略验证 -->\r\n");
        if (!show) {
            sb.append("<!-- fileUpload上传文件 -->\r\n");
            if (uploadMethod.equals("remote")) {
                sb.append("<div class=\"fileUpload plugin_fileUpload\" " + (multi ? "data-append='true'" : ""));
            } else {
                sb.append("<div class=\"localfileUpload plugin_localfileUpload\" " + (multi ? "data-append='true'" : ""));
            }

            setShieldSettings(sb);
            setUplodFileNumber(sb);

            sb.append(">");
            sb.append("<input type=\"button\" class=\"sumbit button\" value=\"" + buttonText
                    + "\"><span class=\"tips\" style='padding-left:5px' >限制大小30M</span></div>");
            sb.append("<!-- fileDiv显示列表 -->\r\n");
            sb.append("<div class=\"fileDiv\">");
        }
        sb.append("<ul class=\"affixDiv-ul ul-item-list\" style=\"float:left\">");
        // 设置图片路径
        showAffixs(sb);
        sb.append("</ul>");
        sb.append("</div>");
        return sb;
    }

    public void showAffixs(StringBuffer sb) {
        List<Map<String, String>> affixList = new ArrayList<>();
        if (StringUtils.isNotEmpty(fileIdValue)) {

            if (fileIdValue.indexOf("#") >= 0) {
                String[] affixIdS = fileIdValue.split("#");
                String[] affixNameS = fileNameValue.split("#");
                for (int i = 0; i < affixIdS.length; i++) {
                    Map<String, String> map = new HashMap<>();
                    map.put("id", affixIdS[i]);
                    map.put("name", affixNameS[i]);
                    affixList.add(map);
                }
            } else {
                Map<String, String> map = new HashMap<>();
                map.put("id", fileIdValue);
                map.put("name", fileNameValue);
                affixList.add(map);
            }
        }
        if (ListUtils.isNotEmpty(affixList)) {
            affixList.forEach(affixMap -> {

                sb.append("<li class=\"multi-li\" selfvalue=\"" + affixMap.get("id") + "\" title=\"" + affixMap.get("name")
                        + "\" style=\"padding: 2px 8px;background: #eee;color: #000;margin-top: 7px\">");
                if (checkImages(affixMap.get("name"))) {
                    sb.append(" <img alt=\"\" src=\"" + affixMap.get("name") + "\" />");
                } else {
                    sb.append(affixMap.get("name"));
                }
                sb.append(" &nbsp;&nbsp;&nbsp;<a class=\"download\" id=\"" + affixMap.get("id") + "\">");
                sb.append("<img src=\"" + pageContext.getServletContext().getAttribute("ctxPath")
                        + "/images/icon/olddownload.png\" title=\"下载\">");
                sb.append("</a>&nbsp;&nbsp;&nbsp;");
                if (!show) {
                    sb.append("<img class=\"multi-liimg del\" src=\"" + pageContext.getServletContext().getAttribute("ctxPath")
                            + "/images/icon/delete.png\" title=\"点击取消\">");
                }
                sb.append("</li>");
            });

        }

    }

    public static boolean checkImages(String path) {
        String imageEmus = "jpg|jpeg|gif|bmp|png";
        String regex = "http://(.*?)/|https://(.*?)/";
        if (StringUtils.isNotEmpty(path) && StringUtils.isNotEmpty(getMatcher(regex, path))) {
            String suffix = path.substring(path.lastIndexOf(".") + 1);
            if (imageEmus.contains(suffix.toLowerCase())) {
                return true;
            }
        }
        return false;
    }

    public static String getMatcher(String regex, String source) {
        String result = "";
        Pattern pattern = Pattern.compile(regex);
        Matcher matcher = pattern.matcher(source);
        while (matcher.find()) {
            result = matcher.group(1);
        }
        return result;
    }

    public StringBuffer setShieldSettings(StringBuffer sb) {
        if (StringUtils.isNotEmpty(shieldSettings)) {
            sb.append("shieldSettings=\"" + shieldSettings + "\"");
        }
        return sb;
    }

    public StringBuffer setUplodFileNumber(StringBuffer sb) {
        if (StringUtils.isNotEmpty(fileIdValue)) {
            String[] fileIdArr = fileIdValue.split("#");
            int fileNum = fileIdArr.length;
            sb.append(" data-filenumber=\"" + fileNum + "\"");
        }
        return sb;
    }

    public StringBuffer setDataHandlerImpl(StringBuffer sb) {
        if (StringUtils.isNotEmpty(dataHandlerImpl)) {
            sb.append(" <input type=\"hidden\" name=\"dataHandlerImpl\"  value=" + dataHandlerImpl + " / >");
        }
        return sb;
    }

    public String getShieldSettings() {
        return shieldSettings;
    }

    public void setShieldSettings(String shieldSettings) {
        this.shieldSettings = shieldSettings;
    }

    public void setDataHandlerImpl(String dataHandlerImpl) {
        this.dataHandlerImpl = dataHandlerImpl;
    }

}
